import React from 'react'
import Header from '@/components/Header'
import '@/pages/chapter.less'
import Link from 'next/link'
import conf from '@/config'
import LazyLoad from 'react-lazyload'
import { inject, observer } from 'mobx-react'
@inject('mangaStore')
@observer
class Manga extends React.Component {
  static async getInitialProps({ query, mobxStore }) {
    if (!mobxStore.mangaStore.manga._id) {
      await Promise.all([
        mobxStore.mangaStore.getMange(query.id),
        mobxStore.mangaStore.getMangeChapters(query.id, query.number)
      ])
    } else {
      await mobxStore.mangaStore.getMangeChapters(query.id, query.number)
    }
    return { query }
  }
  Detail(list) {
    const Comp = []
    for (let k in list) {
      Comp.push(<LazyLoad key={k} throttle={200} height={300}><img src={conf.cdn(`${this.props.query.id}/${list[k]}`)} /></LazyLoad>)
    }
    return Comp
  }
  Chapters(list) {
    const currentNumber = parseInt(this.props.query.number)
    return list.map((item) => {
      return (<Link key={item.number} href={`/chapter?id=${this.props.query.id}&number=${item.number}`}>
        <span className={(item.number === currentNumber) ? 'active' : ''}>{item.number}</span>
      </Link>)
    })
  }
  render() {
    const { query } = this.props
    const { chapters, manga } = this.props.mangaStore
    return (
      <div>
        <Header title={manga.title} description={manga.description} image={conf.cdn(manga.image)} />
        <div className="chapters-detail" key="chapters-detail">
          {(Object.keys(chapters).length > 0) ? this.Detail(chapters) : (<div className="waitforloading">Loading......</div>)}
          <p className="chapters">
            <Link href={`/`}><span>Home</span></Link>
            <Link href={`/manga?id=${query.id}`}><span>Menu</span></Link>
            {this.Chapters(manga.chapters)}
          </p>
        </div>
        <style global jsx>
          {`
            body {
              background: #222222;
            }
         `}
        </style>
      </div>
    )
  }
}

export default Manga
